package pub.elephants.net.body;

import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeoutException;

public class ElephantsCallBack {
    public static ConcurrentMap<String, ElephantsCallBack> requestPool = new ConcurrentHashMap();
    private ElephantsRequest elephantsRequest;
    private ElephantsResponse elephantsResponse;

    // future lock
    private boolean isDone = false;
    private Object lock = new Object();

    public ElephantsCallBack(ElephantsRequest elephantsRequest) {
        this.elephantsRequest = elephantsRequest;
        requestPool.put(elephantsRequest.getRequestId(),this);
    }

    public ElephantsRequest getElephantsRequest() {
        return elephantsRequest;
    }


    public ElephantsResponse getElephantsResponse(long timeoutMillis) throws InterruptedException, TimeoutException {
        if (!isDone) {
            synchronized (lock) {
                try {
                    lock.wait(timeoutMillis);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    throw e;
                }
            }
        }

        if (!isDone) {
            throw new TimeoutException(MessageFormat.format(" netty request timeout at:{0}, request:{1}", System.currentTimeMillis(), elephantsRequest.toString()));
        }
        return elephantsResponse;

    }

    public void setElephantsResponse(ElephantsResponse elephantsResponse) {
        this.elephantsResponse = elephantsResponse;
        synchronized (lock) {
            isDone = true;
            lock.notifyAll();
        }
    }
}
